//
//  RegisterViewController.m
//  跨界收
//
//  Created by MT on 2018/10/27.
//  Copyright © 2018年 gztx. All rights reserved.
//

#import "RegisterViewController.h"

NSString *const kRegisterViewControllerNeedFetchCodeNotificationKey = @"kRegisterViewControllerNeedFetchCode";

@interface RegisterViewController ()

/**
 邀请码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *invitationCodeTextField;

/**
 手机号输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *cellPhoneTextField;

/**
 验证码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;

/**
 勾选协议按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *selectAgreementButton;

/**
 注册按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation RegisterViewController

#pragma mark -- life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initConfigure];
    
    [self buildInterface];
    
    // test
    self.invitationCodeTextField.text = @"54720548163953";
    self.cellPhoneTextField.text = @"13822286029";
}


#pragma mark -- overide
- (void)initConfigure {
    self.title = @"注册";
//    [self.invitationCodeTextField addTarget:self
//                                     action:@selector(textFieldEditingChanged:)
//                           forControlEvents:UIControlEventEditingChanged];
//    [self.cellPhoneTextField addTarget:self
//                                action:@selector(textFieldEditingChanged:)
//                      forControlEvents:UIControlEventEditingChanged];
//    [self.verificationCodeTextField addTarget:self
//                                       action:@selector(textFieldEditingChanged:)
//                             forControlEvents:UIControlEventEditingChanged];
}
- (void)buildInterface {
    
}

#pragma mark -- control event
// 获取验证码
- (IBAction)fetchVerificationCode:(UIButton *)sender {
    [self runVerificationCode:sender];
    
    [self fetchVerificationCode];
}
// 点击勾选协议按钮
- (IBAction)didSelectedAgreementButton:(UIButton *)sender {
    sender.selected = !sender.selected;
}
// 点击跳转预览平台协议
- (IBAction)gotoPreviewAgreement:(UIButton *)sender {
    
}
// 点击开始注册
- (IBAction)doRegister:(UIButton *)sender {
    if ([self checkInputContent]) {
        [self requestForRegister];
    }
}
// 回到登录界面
- (IBAction)backLogin:(UIButton *)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- private methods
// 开启验证码
- (void)runVerificationCode:(UIButton *)sender {
    BOOL isCellPhone = [Tool IsPhoneNumber:self.cellPhoneTextField.text];
    if (!isCellPhone) {
        [self showMBProgressHUDWithWarning:@"请输入正确的手机号"]; return;
    }
    //验证码倒计时
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(timer, ^{
        if(timeout == 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(),
                           ^{
                               sender.userInteractionEnabled = YES;
                               [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                           });
        } else {
            int seconds = timeout % 61;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                NSString *title = [NSString stringWithFormat:@"(%@s)",strTime];
                [sender setTitle:title forState:UIControlStateNormal];
                sender.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(timer);
}

// 获取验证码
- (void)fetchVerificationCode {
    if ([NetworkHelper isNetworkAPIExist]) {
        [self requestForCode];
    } else {
        [NetworkHelper getNetworkAPIWithComplete:^(BOOL result) {
            if (result) {
                [self requestForCode];
            } else {
                [self showMBProgressHUDWithWarning:@"网络出现异常，请检查您的网络状态"];
            }
        }];
    }
}

// 检查输入框非法输入
- (BOOL)checkInputContent {
    BOOL isCorrect = NO;
    
    BOOL isInvitationCode = ![Tool isBlankString:self.invitationCodeTextField.text];
    BOOL isCellPhone = [Tool IsPhoneNumber:self.cellPhoneTextField.text];
    BOOL isVerificationCode = ![Tool isBlankString:self.verificationCodeTextField.text];

    if (!isInvitationCode) {        
        [self showMBProgressHUDWithWarning:@"请输入邀请码"]; return isCorrect = NO;
    }
    
    if (!isCellPhone) {
        [self showMBProgressHUDWithWarning:@"请输入正确的手机号"]; return isCorrect = NO;
    }
    
    if (!isVerificationCode) {
        [self showMBProgressHUDWithWarning:@"请输入验证码"]; return isCorrect = NO;
    }
    
    if (!self.selectAgreementButton.selected) {
        [self showMBProgressHUDWithWarning:[NSString stringWithFormat:@"请阅读并同意%@协议", appName]]; return isCorrect = NO;
    }
    
    return isCorrect = YES;
}


#pragma mark -- request methods
// 请求注册验证码
- (void)requestForCode {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"mobile"] = self.cellPhoneTextField.text;
    dic[@"type"] = @1;
    dic[@"sn"] = [Tool currentTimeStr];
    dic[@"pv"] = @"ios";
    dic[@"v"] = AppVersion;
    dic[@"sign"] = [Tool sortSign:dic];
    [NetworkManager post:[NetworkHelper accountCodeURL] parameters:dic success:^(id object) {
        NSLog(@"requestForCode---> %@", object);
        if (object) {
            NSInteger code = [object[@"status"] integerValue];
            //NSString *message = object[@"msg"];
            if (code == 1) {
                [self showMBProgressHUDWithSuccess:@"短信下发成功"];
            } else {
                [self showMBProgressHUDWithWarning:@"短信下发失败"];
            }
        } else {
            [self showMBProgressHUDWithWarning:@"服务器返回数据错误"];
        }
    } failure:^(NSError *error) {
        [self showMBProgressHUDWithWarning:@"网络出现异常，请检查您的网络状态"];
    }];
}

// 请求注册
- (void)requestForRegister {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"account"] = self.cellPhoneTextField.text;
    dic[@"code"] = self.verificationCodeTextField.text;
    dic[@"invitationCode"] = self.invitationCodeTextField.text;
    dic[@"sign"] = [Tool sortSign:dic];
    [NetworkManager post:[NetworkHelper registerURL] parameters:dic success:^(id object) {
        NSLog(@"requestForRegister---> %@", object);
        if (object) {
            NSInteger code = [object[@"code"] integerValue];
            NSString *message = object[@"message"];
            if (code == 1) {
                [self showMBProgressHUDWithSuccess:@"注册成功"];
                
            } else {
                [self showMBProgressHUDWithWarning:message];
            }
        } else {
            [self showMBProgressHUDWithWarning:@"服务器返回数据错误"];
        }
    } failure:^(NSError *error) {
        [self showMBProgressHUDWithWarning:@"网络出现异常，请检查您的网络状态"];
    }];
}

@end
